package ca.camosun.chatbox.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;

public class ConnectedThread extends Thread {
    private final BluetoothSocket btSocket;
    private final InputStream mmInputStream;
    private final OutputStream mmOutputStream;
 
    public ConnectedThread(BluetoothSocket socket) {
        btSocket = socket;
        
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
 
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }
 
        mmInputStream = tmpIn;
        mmOutputStream = tmpOut;
    }
 
    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
 
        while (true) {
            try {
 
                bytes = mmInputStream.read(buffer);
                String readMessage = new String(buffer, 0, bytes);
                
                //Just send it to the main. Use this mHandler nonsense or don't. Doesn't matter.
                //mHandler.obtainMessage(1, bytes, -1, readMessage).sendToTarget();
                
            } catch (IOException e) {
                break;
            }
        }
    }
 
    public void write(byte[] bytes) {
        try {
            mmOutputStream.write(bytes); 
        } catch (IOException e) { }
    }
 
    public void cancel() {
        try {
            btSocket.close();
        } catch (IOException e) { }
    }
}
